package cool.taomu.toolkit.jsch.service

import com.jcraft.jsch.Session
import cool.taomu.toolkit.jsch.entity.JschConfigEntity.Proxy
import javax.inject.Inject
import org.slf4j.LoggerFactory

class PortForwarding implements AutoCloseable {
	val static LOG = LoggerFactory.getLogger(PortForwarding);
	IJschConnection ds;
	Session session;

	@Inject
	new(IJschConnection ds) {
		this.ds = ds;
	}

	override close() throws Exception {
		if (this.session !== null) {
			LOG.info("关闭SSH  PortForwarding Channel");
			this.session.disconnect
		}
	}

	def portForwarding() {
		/*if (ds.proxy !== null && ds.proxy.size > 0) {
			this.session = ds.resource;
			LOG.info("PortForwarding:{} ", ds.proxy);
			ds.proxy.forEach [
				startPortForwarding(it)
			]
			Runtime.runtime.addShutdownHook(new Thread() {
				override run() {
					PortForwarding.this.close();
				}
			})
		}*/
	}

	protected def void startPortForwarding(Proxy proxy) {
		var int rport = proxy.rport
		var lport = proxy.lport
		if (proxy.type.equals("remote") || proxy.type.equalsIgnoreCase("R")) {
			var lhost = proxy.host
			LOG.info("允许从远程服务器访问本地资源");
			this.session.setPortForwardingR(rport, lhost, lport);
		} else if (proxy.type.equals("local") || proxy.type.equalsIgnoreCase("L")) {
			var rhost = proxy.host
			LOG.info("允许从本地服务器访问远程资源");
			this.session.setPortForwardingL(lport, rhost, rport);
		}
	}

	def getSession() {
		return this.session;
	}
}
